<?php
// public/trainings/view.php
declare(strict_types=1);
require_once __DIR__.'/../../includes/auth.php';
require_once __DIR__.'/../../includes/layout.php';
require_once __DIR__.'/../../includes/flash.php';

$con = mysqli_connect("localhost","root","","ldp_db");
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

require_login();
$user = current_user();
global $pdo;

// Get training ID
$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) { 
    header('Location: /ldp/public/trainings/index.php'); 
    exit; 
}

// Fetch training details
$stmt = $pdo->prepare("SELECT t.*, u.name AS trainer_name
                       FROM training t
                       LEFT JOIN users u ON u.id = t.trainer_id
                       WHERE t.id = ?");
$stmt->execute([$id]);
$training = $stmt->fetch();

if (!$training) { 
    set_flash('warning','Training not found.'); 
    header('Location:/ldp/public/trainings/index.php'); 
    exit; 
}

// Check if user can manage participants
$canManage = in_array($user['role'], ['admin','hr'], true) ||
             ($user['role']==='trainer' && (int)$training['trainer_id']===(int)$user['id']);

// Fetch enrollments
$enr = $pdo->prepare("SELECT e.id, e.user_id, e.status, e.completion_date, u.name, u.email
                      FROM enrollment e
                      JOIN users u ON u.id = e.user_id
                      WHERE e.training_id = ?
                      ORDER BY u.name ASC");
$enr->execute([$id]);
$enrollments = $enr->fetchAll();

// Fetch all employees for adding participants if allowed
$employees = [];
if ($canManage) {
    $employees = $pdo->query("SELECT id, name, position, employee_type FROM personnel WHERE employee_type!='trainer' ORDER BY id ASC")->fetchAll();
}

render_header('Training Details', 'trainings');
$flash = get_flash();
?>

<?php if ($flash): ?>
<div class="alert alert-<?= htmlspecialchars($flash['type']) ?>">
    <?= htmlspecialchars($flash['message']) ?>
</div>
<?php endif; ?>

<style>
/* General Styling */
body { font-family: DejaVu Sans, Arial, sans-serif; font-size: 18px; }
.header { width: 100%; border: 1px solid #000; border-collapse: collapse; margin-bottom: 10px; }
.header td { border: 1px solid #000; text-align: center; vertical-align: middle; }
.header img { height: 70px; }
h2 { text-align:center; margin: 8px 0; }
table { width:100%; border-collapse: collapse; margin-top: 10px; }
th, td { border:1px solid #333; padding:5px 7px; font-size: 18px; }
th { background:#f0f0f0; }

/* Print Styling */
@media print {
    .btn-print, #selectprint { display: none !important; }
    .card2[style*="display: none"] { display: none !important; }
}
</style>

<div class="card3">
  <div class="card-body">
      <a class="btn btn-success btn-print" href="#" onclick="window.print()"><i class="glyphicon glyphicon-print"></i> Print</a>

      <table class="header">
          <tr>
              <td style="width: 15%;"><img src="http://localhost/ldp/public/assets/img/logo.png" style="width:90px;height:90px;"></td>
              <td style="width: 70%;">
                  Republic of the Philippines<br>
                  <strong>DR. EMILIO B. ESPINOSA SR., MEMORIAL STATE COLLEGE OF AGRICULTURE AND TECHNOLOGY</strong><br>
                  Cabitan, Mandaon, Masbate | <a href="http://www.debesmscat.edu.ph">www.debesmscat.edu.ph</a><br>
                  <strong style="font-size:25px;">TRAINING REPORTS</strong>
              </td>
              <td style="width: 15%;"><img src="http://localhost/ldp/public/assets/img/l.png" style="width:90px;height:90px;"></td>
          </tr>
      </table>

      <h2 class="mb-1">Title: <?= htmlspecialchars($training['title']) ?></h2>
      <label>Description</label>
      <p class="text-muted mb-2"><?= nl2br(htmlspecialchars($training['description'])) ?></p>

      <?php
      $traineeId = $training['traineename'];
      $query = mysqli_query($con,"SELECT * FROM personnel WHERE id='$traineeId'") or die(mysqli_error());
      $person = mysqli_fetch_array($query);
      ?>
      <label>Personnel</label>
      <p class="text-muted mb-2"><?= htmlspecialchars($person['name']); ?></p>

      <div class="row">
          <div class="col-md-4"><strong>Schedule:</strong> <?= htmlspecialchars($training['schedule'] ?: 'MTWTFSS') ?></div>
          <div class="col-md-4"><strong>Description:</strong> <?= htmlspecialchars($training['description'] ?: 'ALL') ?></div>
          <div class="col-md-4"><strong>Level of Training:</strong> <?= htmlspecialchars($training['leveloftraining'] ?: 'ALL') ?></div>
          <div class="col-md-4"><strong>LND:</strong> <?= htmlspecialchars($training['lnd'] ?: 'ALL') ?></div>
          <div class="col-md-4"><strong>Trainer:</strong> ____________________</div>
          <div class="col-md-4"><strong>Created:</strong> <?= htmlspecialchars($training['created_at']) ?></div>
      </div>
  </div>
</div>

<!-- Select print control -->
<select name="selectprint" id="selectprint" class="form-control mb-3">
    <option value="enabled">Enabled</option>
    <option value="disabled">Disabled</option>
</select>

<?php if ($canManage): ?>
<div class="card2">
  <div class="card-header"><h3 class="card-title">Add Participants</h3></div>
  <div class="card-body">
    <form class="form-inline" method="post" action="enroll.php">
      <?= csrf_field(); ?>
      <input type="hidden" name="training_id" value="<?= (int)$training['id'] ?>">
      <div class="form-group col-md-6">
        <select name="user_id" class="form-control" style="width:500px;">
          <?php foreach ($employees as $emp): ?>
            <option value="<?= (int)$emp['id'] ?>"><?= htmlspecialchars($emp['name'].' ('.$emp['employee_type'].')') ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <button class="btn btn-primary"><i class="fas fa-user-plus"></i> Add / Training Participants</button>
    </form>
  </div>
</div>
<?php endif; ?>

<div class="card">
  <div class="card-header"><h3 class="card-title">List of Participants</h3></div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table  style="font-size:16px;" class="tablef">
        <thead>
          <tr>
            <th>Name</th>
            <th>Department</th>
            <th style="width:160px;">Status</th>
            <th style="width:160px;">Completion Date</th>
          </tr>
        </thead>
        <tbody>
        <?php
        $query1 = mysqli_query($con,"SELECT * FROM enrollment WHERE training_id='$id'") or die(mysqli_error());
        while($enroll=mysqli_fetch_array($query1)){
            $userId = $enroll['user_id'];
            $queryUser = mysqli_query($con,"SELECT * FROM personnel WHERE id='$userId'") or die(mysqli_error());
            $userRow = mysqli_fetch_array($queryUser);
        ?>
          <tr>
              <td><?= htmlspecialchars($userRow['name']) ?></td>
              <td><?= htmlspecialchars($userRow['department']) ?></td>
              <td><?= htmlspecialchars($enroll['status']) ?></td>
              <td><?= htmlspecialchars($enroll['completion_date']) ?></td>
          </tr>
        <?php } ?>
        </tbody>
      </table>
    </div>
  </div>
</div>


<script>
// Toggle .card2 visibility based on select
const selectPrint = document.getElementById('selectprint');
const card2 = document.querySelector('.card2');
const card = document.querySelector('.card');
const tablef = document.querySelector('.tablef');

function updateCardVisibility() {
    if (!card2) return;
    card2.style.display = (selectPrint.value === 'disabled') ? 'none' : 'block';
	card.style.display = (selectPrint.value === 'disabled') ? 'none' : 'block';
	tablef.style.display = (selectPrint.value === 'disabled') ? 'none' : 'block';
}

updateCardVisibility();
selectPrint.addEventListener('change', updateCardVisibility);
</script>

<?php render_footer(); ?>
